package com.qf.controller;

import com.qf.utils.RedisLockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class SeckillController {
    //1.准备全局商品数据
    public static Map<String,Integer> itemStock=new HashMap<>();
    //2.准备全局订单数据
    public static Map<String,Integer> itemOrder=new HashMap<>();
    @Autowired
    private CuratorFramework cf;
    @Autowired
    private RedisLockUtil redisLockUtil;
    //3.初始化数据
    static {
        //一万件商品
        itemStock.put("IPhone",10000 );
        //目前0订单
        itemOrder.put("IPhone",0);
    }

    /**
     * 秒杀代码
     * @return
     * @throws Exception
     */
    @GetMapping("/kill")
    public String kill(String item) throws Exception{
        //=======zookeeper实现分布式锁，加锁==========
        //创建zookeeper锁对象，在zookeeper中创建一个临时有序节点，名称叫做lock
//        InterProcessMutex lock=new InterProcessMutex(cf,"/lock");
//        if(lock.acquire(1, TimeUnit.SECONDS)){
            if(redisLockUtil.lock(item,String.valueOf(System.currentTimeMillis()),1)){
            //1.扣减库存
            Integer integer = itemStock.get(item);
            if(integer<=0){
                return "商品库存不足";
            }
            Thread.sleep(100);
            //扣减库存
            itemStock.put(item,integer-1);
            //2.创建订单
            Thread.sleep(100);
            itemOrder.put(item, itemOrder.get(item)+1);
            //返回信息下单操作
            //lock.release();

                //======redis解锁
                redisLockUtil.unLock(item);
            return "下单操作ok ,item=" + itemStock.get(item)+"order :"+itemOrder.get(item);

        }else{
            //当前没有获取到锁
            return "不好意思没有抢到IPhone13";
        }
    }
}
